﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ZhCun.SqlServerRestore
{
    public partial class FrmMain : Form
    {
        public FrmMain()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
        }

        RestoreTools Restore { get; } = new RestoreTools();

        private void FrmMain_Load(object sender, EventArgs e)
        {
            txtServer.Text = ConfigurationManager.AppSettings["server"];
            txtUId.Text = ConfigurationManager.AppSettings["uid"];
            txtUpwd.Text = ConfigurationManager.AppSettings["pwd"];
            txtSavePath.Text = ConfigurationManager.AppSettings["savePath"];

            if (txtServer.Text.Trim().Length == 0)
            {
                txtServer.Text = ".";
            }
            if (txtUId.Text.Trim().Length == 0)
            {
                txtUId.Text = "sa";
            }
            if (txtSavePath.Text.Trim().Length == 0)
            {
                txtSavePath.Text = "d:\\SqlData";
            }


            txtUpwd.Focus();
        }

        private void btnAbort_Click(object sender, EventArgs e)
        {
            MessageBox.Show("作者：\t一笑\r\nEmail：\tzhangcunliang@126.com\r\n代码托管：https://gitee.com/zhcun/ORM.git");
        }

        private void txtServer_TextChanged(object sender, EventArgs e)
        {
            Restore.ConnectSuccess = false;
        }

        private void btnTestConn_Click(object sender, EventArgs e)
        {
            string server = txtServer.Text.Trim();
            string uId = txtUId.Text.Trim();
            string pwd = txtUpwd.Text.Trim();
            try
            {
                Restore.SetConnectConfig(server, uId, pwd);
                Restore.TestConnect();
                MessageBox.Show("连接成功!");
            }
            catch (Exception ex)
            {
                MessageBox.Show("连接失败!" + ex.Message);
            }
        }

        private void btnSavePath_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fbd = new FolderBrowserDialog();
            if (fbd.ShowDialog() == DialogResult.OK)
            {
                txtSavePath.Text = fbd.SelectedPath;
            }
        }

        private void BtnOpenFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                txtBakFile.Text = ofd.FileName;
                string safeFileName = Path.GetFileNameWithoutExtension(ofd.FileName); //获取文件名(不含文件扩展名)
                txtNewDbName.Text = safeFileName;
            }
        }

        FrmWait WaitForm { set; get; }

        private void BtnExec_Click(object sender, EventArgs e)
        {
            if (!Restore.ConnectSuccess)
            {
                MessageBox.Show("请先测试数据库连接是否正常!");
                btnTestConn.Focus();
                return;
            }
            if (txtBakFile.Text.Trim().Length <= 0)
            {
                MessageBox.Show("请先选择备份文件.");
                BtnOpenFile.Focus();
                return;
            }
            string newDBName = txtNewDbName.Text.Trim();
            if (newDBName.Trim().Length <= 0)
            {
                MessageBox.Show("数据库名不能为空!");
                txtNewDbName.Focus();
                return;
            }
            string savePath = txtSavePath.Text.Trim();
            if (savePath.Length <= 0)
            {
                MessageBox.Show("保存路径不能为空!");
                txtSavePath.Focus();
                return;
            }

            //查找数据库是否存在
            if (Restore.DatabaseIsExist(newDBName))
            {
                if (MessageBox.Show("数据库已存在,是否删除现有的数据库?", "删除确认", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) != DialogResult.OK)
                {
                    return;
                }
            }
            BtnExec.Enabled = false;
            lblStatus.Text = "正在执行恢复操作,请稍后...";
            Task.Factory.StartNew(ShowWaitForm);
            Task.Factory.StartNew(ExecRestore);
        }

        void ShowWaitForm()
        {
            WaitForm = new FrmWait();
            WaitForm.Size = this.Size;
            WaitForm.Opacity = 0.1;
            WaitForm.Location = this.Location;
            WaitForm.ShowDialog();
        }

        void ExecRestore()
        {
            try
            {
                RestoreModel model = new RestoreModel();
                model.BackupFile = txtBakFile.Text.Trim();
                model.NewDBName = txtNewDbName.Text.Trim();
                model.SaveFullPath = txtSavePath.Text.Trim();
                Restore.RestoreDB(model);
                lblStatus.Text = "恢复成功.";
            }
            catch (Exception ErrInfo)
            {
                lblStatus.Text = "恢复失败×";
                MessageBox.Show(ErrInfo.Message);
            }
            finally
            {
                BtnExec.Enabled = true;
                WaitForm.Close();
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void txtBakFile_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effect = DragDropEffects.Link;
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
        }

        private void txtBakFile_DragDrop(object sender, DragEventArgs e)
        {
            txtBakFile.Text = ((Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString();
            string safeFileName = Path.GetFileNameWithoutExtension(txtBakFile.Text); //获取文件名(不含文件扩展名)
            txtNewDbName.Text = safeFileName;
        }
    }
}